package cn.stylefeng.guns.modular.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.dto.CombineSformDto;
import cn.stylefeng.guns.modular.dto.FuzzySearchSFormDto;
import cn.stylefeng.guns.modular.dto.ScheduleFormDto;
import cn.stylefeng.guns.modular.entity.ScheduleForm;
import cn.stylefeng.guns.modular.entity.ScheduleFormItem;
import cn.stylefeng.guns.modular.entity.ScheduleFrame;
import cn.stylefeng.guns.modular.entity.ScheduleFrameItem;
import cn.stylefeng.guns.modular.service.ScheduleFormItemService;
import cn.stylefeng.guns.modular.service.ScheduleFormService;
import cn.stylefeng.guns.modular.service.ScheduleFrameItemService;
import cn.stylefeng.guns.modular.service.ScheduleFrameService;
import cn.stylefeng.guns.modular.utils.UserMessage;
import cn.stylefeng.guns.modular.utils.WeekBetweenCount;
import cn.stylefeng.guns.modular.wapper.MyscheduleformWrapper;
import cn.stylefeng.guns.sys.modular.system.warpper.UserWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.datascope.DataScope;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/myScheduleForm")
public class MyScheduleFormController extends BaseController {
    @Autowired
    private ScheduleFormService scheduleFormService;
    @Autowired
    private ScheduleFrameService scheduleFrameService;
    @Autowired
    private ScheduleFrameItemService scheduleFrameItemService;
    @Autowired
    private ScheduleFormItemService scheduleFormItemService;


    /**
     * 加载我的日程表页面
     *
     * @return
     */
    @RequestMapping(value = "/showScheduleForm")
    public String loadScheduleForm() {
        return "/scheduleform/myScheduleForm.html";
    }

    /**
     * 显示所有日程表
     *
     * @return
     */
    @RequestMapping(value = "/showScheduleForm",method = RequestMethod.POST)
    @ResponseBody
    public Object showScheduleForm(FuzzySearchSFormDto fuzzySearchSFormDto ,Model model) {

        System.out.println("================="+fuzzySearchSFormDto);
        if (fuzzySearchSFormDto.getKeyword()!=null&fuzzySearchSFormDto.getKeyword()!=""){
            fuzzySearchSFormDto.setKeyword(fuzzySearchSFormDto.getKeyword().trim());
        }

        //得到用户id
        long userId = UserMessage.getUserId();
        Page<Map<String, Object>> showScheduleForm = scheduleFormService.fuzzySearchSForm(fuzzySearchSFormDto,userId);
        Page wrapped = new MyscheduleformWrapper(showScheduleForm).wrap();
        //分页显示
        LayuiPageInfo layuiPageInfo =LayuiPageFactory.createPageInfo(wrapped);
        model.addAttribute("count",layuiPageInfo.getCount());
        return  layuiPageInfo;
    }

    /**
     * 选择框架并进行保存日程表
     *
     * @param selframe
     * @param sformName
     * @return
     */
    @RequestMapping(value = "/selectframe", method = RequestMethod.POST)
    @ResponseBody
    public String selectframeAndSave(String selframe, String sformName, String share, String draft) {

        //设置日程表信息
        ScheduleForm scheduleForm = new ScheduleForm();
        scheduleForm.setSformName(sformName);
        scheduleForm.setUserId(UserMessage.getUserId());
        scheduleForm.setIsShare(share);
        scheduleForm.setDraft(draft);
        scheduleForm.setSframeId(Integer.parseInt(selframe));
        scheduleForm.setCreatTime(new Date());
        ScheduleForm scheduleForm1 = scheduleFormService.selectScheduleFormByAllName(sformName, UserMessage.getUserId());
        if (scheduleForm1 != null) {
            return "日程名不能重复！";
        }
        int rows = scheduleFormService.saveScheduleForm(scheduleForm);
        if (rows == 1) {
            System.out.println("保存日程表成功！");
            return "保存日程表成功！";
        } else {
            System.out.println("保存日程表失败！");
            return "保存日程表失败！";
        }
    }

    /*    *//**
     * 选择完框架后到加载创建日程表界面
     * @return
     *//*
    @RequestMapping(value = "/creatform")
    public String locadCreateForm(){
        return "pages/scheduleform/addform.html";
    }*/


    /*    *//**
     * 选择完框架后到加载创建日程表界面（ajax）
     * @return
     *//*
    @RequestMapping(value = "/createform" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> creatForm(String sframeName){
        long userId= UserMessage.getUserId();

        //根据选择的框架id得到框架信息
        ScheduleFrame scheduleFrame= scheduleFrameService.selectScheduleFrameByName(sframeName,userId);
        //根据选择的框架id得到所有框架项个数和信息
        List<ScheduleFrameItem> scheduleFrameItems= scheduleFrameItemService.selectSframeItemBySframeId(scheduleFrame.getSframeId());
        int count= scheduleFrameItemService.selectSframeItemCountBySframeId(scheduleFrame.getSframeId());
        Map<String,Object> map =new HashMap<>();
        map.put("scheduleFrameItems",scheduleFrameItems);
        map.put("scheduleFrameItems",scheduleFrameItems);
        map.put("count",count);
        return map;
        *//*return "pages/scheduleform/addform.html";*//*
    }*/


    /**
     * 保存日程表
     * 先保存日程表
     * 再设置日程表项的sformId
     *
     * @return
     */
    @RequestMapping("saveSform")
    public String saveSform(ScheduleFormDto scheduleFormDto, int sframeId) {
        ScheduleForm scheduleForm = new ScheduleForm();
        scheduleForm.setSformName(scheduleFormDto.getSformName());
        scheduleForm.setSframeId(sframeId);
        scheduleForm.setIsShare(scheduleFormDto.getIsShare());
        scheduleForm.setDraft(scheduleFormDto.getDraft());
        scheduleForm.setUserId(UserMessage.getUserId());
        scheduleForm.setCreatTime(new Date());

        int rows = scheduleFormService.saveScheduleForm(scheduleForm);
        if (rows == 1) {

            //通过名字查出日程表信息
            ScheduleForm scheduleFormByName = scheduleFormService.selectScheduleFormByAllName(scheduleFormDto.getSformName(), UserMessage.getUserId());
            //  设置日程项的日程表id
            scheduleFormItemService.setFormId(scheduleFormByName.getSformId());
            return "保存成功！";

        } else {
            return "保存失败！";
        }
    }


    /**
     * 选中删除的日程表
     * 先删除其日程项
     * 再删除日程表
     *
     * @param sformId
     * @return
     */
    @RequestMapping("deleteSformBySformId")
    @ResponseBody
    public String deleteSformBySformId(String sformId) {
        System.out.println("===================="+sformId);
        scheduleFormItemService.deleteBySformId(Integer.parseInt(sformId));
        int formRow = scheduleFormService.deletScheduleFormBy(Integer.parseInt(sformId));
        if (formRow == 1) {
            System.out.println("删除成功！");
            return "删除日程表成功！";
        } else {
            return "删除失败！";
        }
    }

    /**
     * 根据sformId复制日程表
     *
     * @param sformId
     * @return
     */
    public String copySform(int sformId, String sformName) {
        long userId = UserMessage.getUserId();
        ScheduleForm scheduleForm = scheduleFormService.selectSformBySformId(sformId);
        //查询输入的是否重名
        ScheduleForm scheduleFormByNameIsSame = scheduleFormService.selectScheduleFormByAllName(sformName, userId);
        //若不重名
        if (scheduleFormByNameIsSame == null) {
            scheduleForm.setSformName("sformName");
            //保存复制的日程表
            scheduleFormService.saveScheduleForm(scheduleForm);
            //查看复制的日程表
            ScheduleForm scheduleFormByName = scheduleFormService.selectScheduleFormByAllName(sformName, userId);
            //根据sformId查询该表所有日程项
            List<ScheduleFormItem> scheduleFormItems = scheduleFormItemService.selectSformItemBySformId(scheduleFormByName.getSformId());
            for (ScheduleFormItem scheduleFormItem : scheduleFormItems) {
                scheduleFormItem.setSformId(scheduleFormByName.getSformId());
                int rows = scheduleFormItemService.saveScheduleFormItem(scheduleFormItem);
                if (rows == 1) {
                    System.out.println("复制成功！");
                } else {
                    System.out.println("复制失败！");
                }
            }

        } else {
            System.out.println("名字不能重复！");
        }

        return null;
    }

    /**
     * 修改日程表
     * 只是修改了日程表，与日程项无关
     *
     * @param sformId 选中的日程表Id
     * @return
     */
    @RequestMapping("reviseSform")
    public String reviseSform(String sformId, Model model) {

        //根据sformId查看日程表
        ScheduleForm scheduleForm = scheduleFormService.selectSformBySformId(Integer.parseInt(sformId));
        String sformName = scheduleForm.getSformName();
        String draft = scheduleForm.getDraft();
        String isShare=scheduleForm.getIsShare();
        model.addAttribute("sformName", sformName);
        model.addAttribute("draft", draft);
        model.addAttribute("sformId", sformId);
        model.addAttribute("isShare",isShare);

        return "/scheduleform/reviseSform.html";
    }

    /**
     * 保存修改后的日程表
     * @return
     */
    @RequestMapping(value = "saveReviseSform", method = RequestMethod.POST)
    @ResponseBody
    public String saveReviseSform(String sformName, String draft, String sformId,String isShare ) {
        System.out.println("======================"+isShare+draft);
        ScheduleForm scheduleForm = scheduleFormService.selectScheduleFormByAllName(sformName, UserMessage.getUserId());
        if (scheduleForm != null) {
            System.out.println("日程表名不能相同！");
            return "日程表名不能相同！";
        }
        int rows = scheduleFormService.updateSform(sformName, draft, Integer.parseInt(sformId));
        if (rows == 1) {
            return "日程表修改成功！";
        } else {
            return "日程表修改失败！";
        }


    }

    /**
     *
     * 修改日程表的共享状态
     * @param sformId
     * @param status
     * @return
     */
    @RequestMapping("setShare")
    @ResponseBody
    public String setShare(String sformId,String status){
      int isShare=  scheduleFormService.setSformShare(status,Integer.parseInt(sformId));
      if (isShare==1){
          return "修改成功！";
      }else {
          return "修改失败！";
      }
    }

    /**
     * 加载合并页面
     * @param sformId
     * @param model
     * @return
     */
    @RequestMapping("loadcombineSform")
    public String loadcombineSform(String sformId, Model model) {
        System.out.println("================" + sformId);
        model.addAttribute("sformId", sformId);
        return "/scheduleform/combineSform.html";

    }

    /**
     * 加载日程表页面的日程列表
     *
     * @return
     */
    @RequestMapping("loalAllMySform")
    @ResponseBody
    public List<ScheduleForm> loalAllMySform() {
        List<ScheduleForm> sformList = scheduleFormService.selectById(UserMessage.getUserId());
        return sformList;
    }

    /**
     * 合并日程表
     *
     * @param combineSformDto
     * @return
     */
    @RequestMapping("/combineSform")
    @ResponseBody
    public String combineSform(CombineSformDto combineSformDto) {
        System.out.println("===============================================" + combineSformDto);
        long userId = UserMessage.getUserId();
        //根据两个日程表的sformId判断是否是同一个基于框架
        ScheduleForm scheduleForm1 = scheduleFormService.selectSformBySformId(Integer.parseInt(combineSformDto.getSform1()));
        System.out.println("=========================" + scheduleForm1);
        ScheduleForm scheduleForm2 = scheduleFormService.selectSformBySformId(Integer.parseInt(combineSformDto.getSform2()));
        System.out.println("=========================" + scheduleForm2);
        if (scheduleForm1.getSframeId() != scheduleForm2.getSframeId()) {
            System.out.println("两个日程表不是基于同一个框架，不能合并！");
            return "两个日程表不是基于同一个框架，不能合并！";
        }
        System.out.println("=================基于同一个框架,可以合并");
        //基于同一个框架,可以合并
        //框架共有多少框架项
        int count = scheduleFrameItemService.selectSframeItemCountBySframeId(scheduleForm1.getSframeId());
        System.out.println("==================" + count);
        //定义二重循环的次数
        int countSecond = 0;
        //定义一个list集合用来装发生异常冲突的日程项
        List<ScheduleFormItem> clashSformItems = new ArrayList();
        //定义一个list集合用来装没有发生异常冲突的日程项
        List<ScheduleFormItem> canCombineSformItems = new ArrayList();
        System.out.println("=======================开始循环");
        List<ScheduleFormItem> list1 =null;
        List<ScheduleFormItem> list2 =null;
        for (int i = 1; i <= count; i++) {
            //根据序号得到日程项
            list1 = scheduleFormItemService.selectSformItemBySformIdAndItemSerial(Integer.parseInt(combineSformDto.getSform1()), i);
            list2 = scheduleFormItemService.selectSformItemBySformIdAndItemSerial(Integer.parseInt(combineSformDto.getSform2()), i);

            System.out.println("========================" + i + "次=========");
            System.out.println("=======================" + list1);
            System.out.println("====================" + list2);
            //以小的为参照物
            if (list1.size() <= list2.size()) {
                countSecond = list1.size();
            } else {
                countSecond = list2.size();
            }
            System.out.println("==========================" + countSecond);

           //如果两列日程序号的日程项互斥，就是都不相同，直接跳出本次循环
                if (countSecond==0){
/*                if (list1.size()!=0){
                    System.out.println("=============="+list1);
                    for (ScheduleFormItem scheduleFormItenAll1:list1) {
                        canCombineSformItems.add(scheduleFormItenAll1);
                    }
                }
                if (list2.size()!=0){
                    for (ScheduleFormItem scheduleFormItemAll2:list2) {
                        canCombineSformItems.add(scheduleFormItemAll2);
                    }
                }*/
               continue;
            }
            for (int j = 0; j < countSecond; j++) {
                for (int k=0;k<(list1.size()>=list2.size()?list1.size():list2.size());k++){
                    //第三重循环：以小的为二重循环次数
                    if (list1.size()<=list2.size()){
                        //若第一个比较日程项比较小，第一个作为二重循环次数
                        if (list1.get(j).getSformItemDate().equals(list2.get(k).getSformItemDate())){
                            //发生冲突，跳出本次循环
                            clashSformItems.add(list1.get(j));
                            clashSformItems.add(list2.get(k));
                            break;
                        }

                    }else {
                        //若第一个比较日程项比较小，第一个作为二重循环次数
                        if (list2.get(j).getSformItemDate().equals(list1.get(k).getSformItemDate())){
                            //发生冲突，跳出本次循环
                            clashSformItems.add(list2.get(j));
                            clashSformItems.add(list1.get(k));
                            break;
                        }
                    }
                }
            }
        }
        if (clashSformItems.size()>0){
            System.out.println("==================="+clashSformItems);
            System.out.println("不能合并，有冲突项");

            return "不能合并，有冲突项！";

        }else {
            System.out.println("可以合并，不发生冲突");
            List<ScheduleFormItem> listAll1 = scheduleFormItemService.selectSformItemBySformId(Integer.parseInt(combineSformDto.getSform1()));
            List<ScheduleFormItem> listAll2 = scheduleFormItemService.selectSformItemBySformId(Integer.parseInt(combineSformDto.getSform2()));

            for (ScheduleFormItem scheduleFormItenAll1 : listAll1) {
                canCombineSformItems.add(scheduleFormItenAll1);
            }
            for (ScheduleFormItem scheduleFormItemAll2 : listAll2) {
                canCombineSformItems.add(scheduleFormItemAll2);
            }
            System.out.println("================================123" + canCombineSformItems);
            //不发生冲突，可以合并
            System.out.println("=================="+combineSformDto.getCombineSformName());
            ScheduleForm scheduleForm =scheduleFormService.selectScheduleFormByAllName(combineSformDto.getCombineSformName(),userId);
            if (scheduleForm!=null){
                System.out.println("日程表名字不能重复！");
                return "日程表名字不能重复！";
            }
            ScheduleForm combineScheduleForm=new ScheduleForm();
            combineScheduleForm.setUserId(userId);
            combineScheduleForm.setSformName(combineSformDto.getCombineSformName());
            combineScheduleForm.setDraft(combineSformDto.getDraft());
            combineScheduleForm.setIsShare(combineSformDto.getShare());
            combineScheduleForm.setCreatTime(new Date());
            combineScheduleForm.setSframeId(scheduleForm1.getSframeId());
            int rows= scheduleFormService.saveScheduleForm(combineScheduleForm);
            if (rows!=1){
                System.out.println("添加日程表失败！");
            }
            //查询添加的表信息
            ScheduleForm scheduleFormAdd =scheduleFormService.selectScheduleFormByAllName(combineSformDto.getCombineSformName(),userId);
/*                   //根据sformId得到所有的日程项
                   List<ScheduleFormItem> allSformItem1= scheduleFormItemService.selectSformItemBySformId(Integer.parseInt(combineSformDto.getSform1()));
                   List<ScheduleFormItem> allSformItem2=scheduleFormItemService.selectSformItemBySformId(Integer.parseInt(combineSformDto.getSform2()));*/
            //把上面两个的日程项加到合并的日程表中
            for (ScheduleFormItem scheduleFormItemEach1:canCombineSformItems) {
                scheduleFormItemEach1.setSformId(scheduleFormAdd.getSformId());
                scheduleFormItemService.saveScheduleFormItem(scheduleFormItemEach1);
            }
            return "日程表合并成功！";
        }
    }

    /**
     * 查看日程表信息(插件)
     * @return
     */
    @RequestMapping("checkScheduleForm")
    public String checkScheduleForm(String sformId,Model model){
        System.out.println("==================aSG=="+sformId);
        ScheduleForm scheduleForm =scheduleFormService.selectSformBySformId(Integer.parseInt(sformId));
        System.out.println("============123123123==========="+scheduleForm);
        String sformName=scheduleForm.getSformName();
        int sframeId=scheduleForm.getSframeId();
        int sformIdInt=scheduleForm.getSformId();
        ScheduleFrame scheduleFrame =scheduleFrameService.selectScheduleFrameById(sframeId);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String startDate=sdf.format( scheduleFrame.getStartDate());
        String stopDate=sdf.format( scheduleFrame.getStopDate());

        String dateAll=startDate+"\t——"+"\t"+stopDate;
        model.addAttribute("scheduleForm",scheduleForm);
        model.addAttribute("sformName",sformName);
        model.addAttribute("sframeId",sframeId);
        model.addAttribute("sformIdInt",sformIdInt);
        model.addAttribute("dateAll",dateAll);



        return "/scheduleform/checkScheduleForm.html";
    }
    /**
     * 查看日程表信息
     * @return
     */
    @RequestMapping(value = "checkScheduleForm" ,method = RequestMethod.POST)
    @ResponseBody
    public JSONObject loadCheckScheduleForm2(String sformId){
        System.out.println("=============="+sformId);
        int daysCount=0;
        ScheduleForm scheduleForm =scheduleFormService.selectSformBySformId(Integer.parseInt(sformId));
        System.out.println("============================"+scheduleForm);
        //得到该日程表的所有日程项
        List<ScheduleFormItem> scheduleFormItems= scheduleFormItemService.selectSformItemBySformId(Integer.parseInt(sformId));
        System.out.println("==========================123=="+scheduleFormItems);
        System.out.println("======12312======"+scheduleForm.getSframeId());
        ScheduleFrame scheduleFrame =scheduleFrameService.selectScheduleFrameById(scheduleForm.getSframeId());
        System.out.println("=============scheduleFrame====123===="+scheduleFrame);

//        //得到周数量
//        String weekCount= scheduleFrame.getWeekCount();
        Date startDate=scheduleFrame.getStartDate();
        Date stopDate=scheduleFrame.getStopDate();
        try {
            //两个日期相隔多少天
            daysCount= WeekBetweenCount.daysBetween(startDate,stopDate);
            System.out.println("========================="+daysCount);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Map<String,Object> map =new HashMap<>();
        map.put("scheduleForm",scheduleForm);
        map.put("daysCount",daysCount);
/*        map.put("weekCount",weekCount);*/
        map.put("scheduleFormItems",scheduleFormItems);

        JSONObject result = JSONObject.parseObject(JSON.toJSONString(map));
        System.out.println("==========123=====123=lsw====="+result);

        return result;
    }
    /*================================================================================================*/


    /**
     * 查看日程表信息
     * @return
     */
    @RequestMapping("checkScheduleForm2")
    public String checkScheduleForm2(String sformId,Model model){
        System.out.println("==================aSG=="+sformId);
        ScheduleForm scheduleForm =scheduleFormService.selectSformBySformId(Integer.parseInt(sformId));
        System.out.println("======================="+scheduleForm);
       String sformName=scheduleForm.getSformName();
       int sformIdInt=scheduleForm.getSformId();
        model.addAttribute("sformName",sformName);
        model.addAttribute("sformIdInt",sformIdInt);
        return "/scheduleform1.html";
    }

    /**
     * 查看日程表信息
     * @return
     */
    @RequestMapping(value = "checkScheduleForm2" ,method = RequestMethod.POST)
    @ResponseBody
    public JSONObject loadScheckScheduleForm(String sformId){
        System.out.println("=============="+sformId);
        int daysCount=0;
        ScheduleForm scheduleForm =scheduleFormService.selectSformBySformId(Integer.parseInt(sformId));
        System.out.println("============================"+scheduleForm);
        //得到该日程表的所有日程项
        List<ScheduleFormItem> scheduleFormItems= scheduleFormItemService.selectSformItemBySformId(Integer.parseInt(sformId));
        System.out.println("==========================123=="+scheduleFormItems);
        ScheduleFrame scheduleFrame =scheduleFrameService.selectScheduleFrameById(scheduleForm.getSframeId());


        //得到周数量
        String weekCount= scheduleFrame.getWeekCount();
        Date startDate=scheduleFrame.getStartDate();
        Date stopDate=scheduleFrame.getStopDate();
        try {
            //两个日期相隔多少天
            daysCount= WeekBetweenCount.daysBetween(startDate,stopDate);
            System.out.println("========================="+daysCount);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Map<String,Object> map =new HashMap<>();
        map.put("scheduleForm",scheduleForm);
        map.put("daysCount",daysCount);
        map.put("weekCount",weekCount);
        map.put("scheduleFormItems",scheduleFormItems);

        JSONObject result = JSONObject.parseObject(JSON.toJSONString(map));
        System.out.println("==========123==========="+result);

        return result;
    }




}